package com.meteor.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.meteor.api.feign.system.SystemFeign;
import com.meteor.api.feign.system.dto.SysMerchantDTO;
import com.meteor.api.feign.system.dto.SysOrgDTO;
import com.meteor.convert.CommunityConvert;
import com.meteor.convert.ComplaintConvert;
import com.meteor.entity.Building;
import com.meteor.entity.Community;
import com.meteor.entity.Complaint;
import com.meteor.framework.common.base.ResponseData;
import com.meteor.framework.common.constant.Constant;
import com.meteor.framework.common.enums.UserAdminEnum;
import com.meteor.framework.common.exception.ServerException;
import com.meteor.framework.common.utils.PageResult;
import com.meteor.framework.mybatis.service.impl.BaseServiceImpl;
import com.meteor.framework.security.user.SecurityUser;
import com.meteor.mapper.BuildingMapper;
import com.meteor.mapper.CommunityMapper;
import com.meteor.mapper.ComplaintMapper;
import com.meteor.query.CommunityQuery;
import com.meteor.query.ComplaintQuery;
import com.meteor.query.OrgAndCommunityQuery;
import com.meteor.service.BuildingService;
import com.meteor.service.CommunityService;
import com.meteor.service.ComplaintService;
import com.meteor.vo.CommunityVO;
import com.meteor.vo.ComplaintVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lynn
 * @date 2024/1/22
 */


@Service
@AllArgsConstructor
public class CommunityServiceImpl extends BaseServiceImpl<CommunityMapper, Community> implements CommunityService {


    private final SystemFeign systemFeign;

    private final BuildingService buildingService;


    @Override
    public void save(CommunityVO vo) {

        Community  entity= CommunityConvert.INSTANCE.convert(vo);

        if(!SecurityUser.getUser().getUsername().equalsIgnoreCase(UserAdminEnum.ADMIN.getValue())){

            if(ObjectUtils.isEmpty(vo.getMerchantId())){
                entity.setMerchantId(SecurityUser.getUser().getMerchantId());
            }

            if(ObjectUtils.isEmpty(vo.getOrgId())){
                entity.setOrgId(SecurityUser.getUser().getOrgId());
            }
        }else{

            if(ObjectUtils.isEmpty(vo.getOrgId())) {
                throw new ServerException("请选择机构");
            }
            ResponseData responseData = JSON.parseObject(systemFeign.orgMerchant(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysMerchantDTO sysMerchantDTO = JSON.parseObject(responseData.getData().toString(),SysMerchantDTO.class);
                entity.setMerchantId(sysMerchantDTO.getId());
            }
            entity.setOrgId(vo.getOrgId());
            /*if(ObjectUtils.isEmpty(vo.getMerchantId())) {
                throw new ServerException("请选择商户");
            }*/
        }

        if(!ObjectUtils.isEmpty(vo.getOrgId())){
            ResponseData responseData = JSON.parseObject(systemFeign.getOrg(vo.getOrgId()),ResponseData.class);
            if(!ObjectUtils.isEmpty(responseData.getData())){
                SysOrgDTO sysOrgDTO =  JSON.parseObject(responseData.getData().toString(), SysOrgDTO.class);
                if(sysOrgDTO.getLevel().equals(1)){
                    throw new ServerException("最上级机构不允许新增社区");
                }
            }
        }


        OrgAndCommunityQuery query = new OrgAndCommunityQuery();
        query.setOrgId(vo.getOrgId());
        List<CommunityVO> communityVOS = orgCommunity(query);
        if(!ObjectUtils.isEmpty(communityVOS)){
            throw new ServerException("该机构下已存在社区");
        }

//        entity.setMerchantId(SecurityUser.getUser().getMerchantId());
//        entity.setOrgId(SecurityUser.getUser().getOrgId());

        baseMapper.insert(entity);
    }

    @Override
    public void update(CommunityVO communityVO) {
        Community community = CommunityConvert.INSTANCE.convert(communityVO);
        if (ObjectUtils.isEmpty(community.getId())) {
            throw new ServerException("修改失败，id为空");
        }
        baseMapper.updateById(community);

    }

    @Override
    public CommunityVO getCommunity(String id) {
        return CommunityConvert.INSTANCE.convert(baseMapper.selectById(id));
    }

    @Override
    public List<CommunityVO> getCommunityVOList(CommunityQuery query) {

        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getCommunityName()), Community::getCommunityName, query.getCommunityName());
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityCode()), Community::getCommunityCode, query.getCommunityCode());
        // 数据权限
        dataScopeWrapper(wrapper);
        List<Community> complaints = baseMapper.selectList(wrapper);

        return CommunityConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public PageResult<CommunityVO> pageCommunityVO(CommunityQuery query) {

        // 查询参数
        Map<String, Object> params = getParams(query);

        // 分页查询
        IPage<Community> page = getPage(query);
        params.put(Constant.PAGE, page);

        // 数据列表
        List<CommunityVO> list = baseMapper.getList(params);

        return new PageResult<>(list, page.getTotal());

//        IPage<Complaint> page = baseMapper.selectPage(getPage(query), getWrapper(query));
//
//        return new PageResult<ComplaintVO>(ComplaintConvert.INSTANCE.convertList(page.getRecords()), page.getTotal());
    }

    @Override
    public void delete(String id) {
        LambdaQueryWrapper<Building> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Building::getCommunityId, id);
        wrapper.eq(Building::getDeleted,0);
        List<Building> bs =  buildingService.list(wrapper);
        if(!ObjectUtils.isEmpty(bs)){
            throw new ServerException("该社区下存在楼栋，无法删除");
        }

        removeById(id);
    }

    @Override
    public List<CommunityVO> orgCommunity(OrgAndCommunityQuery query) {
        QueryWrapper<Community> wrapper = new QueryWrapper<>();
        wrapper.eq("org_id", query.getOrgId());
        wrapper.eq("deleted",0);
        return CommunityConvert.INSTANCE.convertList(list(wrapper));
    }

    @Override
    public List<CommunityVO> getList(CommunityQuery query) {
        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getCommunityName()), Community::getCommunityName, query.getCommunityName());
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityCode()), Community::getCommunityCode, query.getCommunityCode());
        wrapper.eq(Community::getDeleted,0);

        List<Community> complaints = baseMapper.selectList(wrapper);

        return CommunityConvert.INSTANCE.convertList(complaints);
    }

    @Override
    public List<CommunityVO> getCommunityList(List<String> ids) {
        if(!ObjectUtils.isEmpty(ids)){
            LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(Community::getId, ids);
            wrapper.eq(Community::getDeleted,0);
            return CommunityConvert.INSTANCE.convertList(list(wrapper));
        }
        return null;
    }

    private Map<String, Object> getParams(CommunityQuery query) {
        Map<String, Object> params = new HashMap<>();
        params.put("communityName", query.getCommunityName());
        params.put("communityCode", query.getCommunityCode());

        // 数据权限
        params.put(Constant.DATA_SCOPE, getDataScope1("t1", null,"pf_community"));

        return params;
    }

    private Wrapper<Community> getWrapper(CommunityQuery query){
        LambdaQueryWrapper<Community> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(query.getCommunityName()), Community::getCommunityName, query.getCommunityName());
        wrapper.eq(StrUtil.isNotBlank(query.getCommunityCode()), Community::getCommunityCode, query.getCommunityCode());


        // 数据权限
        dataScopeWrapper(wrapper);

        return wrapper;
    }
}
